package mysql

import (
	"gorm.io/gorm"
)

type House struct {
	gorm.Model
	UserId      int64  `gorm:"type:int;index;comment:用户id"`
	HouseName   string `gorm:"type:varchar(20);not null;comment:房源名称"`
	HousePrice  int64  `gorm:"type:int(11);comment:房源价格"`
	Floor       string `gorm:"type:varchar(10);not null;comment:楼层"`
	Acreage     int64  `gorm:"type:int;not null;comment:面积"`
	Address     string `gorm:"type:varchar(50);not null;comment:地址"`
	HouseType   string `gorm:"type:varchar(30);not null;comment:房源类型"`
	HouseStatus int64  `gorm:"type:tinyint(1);default:1;comment:房源状态:1待出租,2:上架,3:下架"`
}

func (h *House) Create() error {
	return Db.Create(&h).Error
}
func (h *House) HouseView(houseId int64) error {
	return Db.Where("id = ?", houseId).Limit(1).Find(&h).Error
}

//func (h *House) UpdateHouse() error {
//	return Db.Debug().Model(&House{}).Updates(&House{
//		Model:       gorm.Model{ID: h.ID},
//		UserId:      h.UserId,
//		HouseName:   h.HouseName,
//		HousePrice:  h.HousePrice,
//		Floor:       h.Floor,
//		Acreage:     h.Acreage,
//		Address:     h.Address,
//		HouseType:   h.HouseType,
//		HouseStatus: h.HouseStatus,
//	}).Limit(1).Find(&h).Error
//}

func (h *House) HouseList(keyword string, page, pageSize, starPrice, endPrice int64) (HouseList []*House, err error) {
	db := Db.Debug()
	if starPrice > 0 {
		db = db.Where("price >= ?", starPrice)
	}
	if endPrice < 0 {
		db = db.Where("price <= ?", endPrice)
	}
	err = Db.Where("house_name = like", "%"+keyword+"%").Where("house_status = 2").Scopes(Paginate(page, pageSize)).Order("price desc").Limit(1).Find(&h).Error
	return
}
func Paginate(page, pageSize int64) func(Db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(int(offset)).Limit(int(pageSize))
	}
}
